package com.zhouyibike.uu.ui.activity.mywallet;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.CheckPwdResult;
import com.zhouyibike.uu.entity.DatanullResult;
import com.zhouyibike.uu.entity.QRCodeForPaymentResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.TXCircleImageView;
import com.zhouyibike.uu.utils.Base64Utils;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.ImgUtils;
import com.zhouyibike.uu.utils.RSAUtils;
import com.zhouyibike.uu.utils.TextUtils;

import java.security.PublicKey;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

public class SaomiaoSuccessfukuanActivity extends BaseActivity implements View.OnClickListener {

    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private ImageView iv_quxiao_dismis, zhifu2_iv_quxiao_dismis;
    private TextView tv_money, pricae_tvnum,xingname;
    private Button btn_sure, btn_detail;
    private EditText zhifu_inputnum;
    private Dialog xxdialog, xxdialog2;
    private LinearLayout zhifufubujuly;
    private Button saomiao_surezhifubt;
    private EditText mima;
    private String gongyao = "";
    private String shoukuanname = "";
    private String shoukuanphone = "";
    private String shoukuanpicurl = "zy";
    private String shoukuanyiquanshu = "";
    private int zhifujieguonum = 0;
    private TXCircleImageView shoukuanreniv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhifusaomiao_success);
        shoukuanname=getIntent().getStringExtra("shoukuanname");
        shoukuanphone=getIntent().getStringExtra("shoukuanphone");
        shoukuanpicurl=getIntent().getStringExtra("shoukuanpicurl");
        initView();
        setDialog();
        setDialog2();
        initListener();
//        EditUtils.seteditopen(zhifu_inputnum);
        zhifu_inputnum.setFocusable(true);
        zhifu_inputnum.setFocusableInTouchMode(true);
        zhifu_inputnum.requestFocus();
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        getgongyaoMsg();
    }
    private void initView() {
        shoukuanreniv= (TXCircleImageView) findViewById(R.id.shoukuanreniv);
        xingname= (TextView) findViewById(R.id.xingname);
        xingname.setText("*"+shoukuanname.substring(1));
        Picasso.with(this).load(shoukuanpicurl).transform(ImgUtils.Picassocompress(shoukuanreniv)).error(R.mipmap.head_moren).placeholder(R.mipmap.head_moren).into(shoukuanreniv);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("转券");
        zhifu_inputnum = (EditText) findViewById(R.id.zhifu_inputnum);
        btn_sure = (Button) findViewById(R.id.zhifu_inputnum_sure);
        zhifufubujuly = (LinearLayout) findViewById(R.id.zhifufubujuly);

    }

    private void initListener() {
        mBtnBack.setOnClickListener(this);
        btn_sure.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.zhifu_inputnum_sure:
                if (gongyao.equals("")) {
                    getgongyaoMsg();
                    return;
                } else {

                }
                if (TextUtils.isNullorEmpty(zhifu_inputnum.getText().toString())) {
                    toastShow("请输入正确的翼券数量");

                } else  if (!TextUtils.isNullorEmpty(zhifu_inputnum.getText().toString())&&Double.parseDouble(zhifu_inputnum.getText().toString())==0) {
                    toastShow("翼券数量不能小于1");
                }else{

                    if (zhifu_inputnum.getText().toString()!=null&&Double.parseDouble(zhifu_inputnum.getText().toString())>0) {
                        saomiao_surezhifubt.setEnabled(true);
                        xxdialog.show();
                        DecimalFormat df = new DecimalFormat("######0");
                        pricae_tvnum.setText(df.format(Double.parseDouble(zhifu_inputnum.getText().toString()))+"");
                    } else {
                        saomiao_surezhifubt.setEnabled(false);
                    }
                }
                break;
        }
    }

    private void setDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        final View headview = inflater.inflate(R.layout.newwalletzhifu_show_dialog, zhifufubujuly, false);
        xxdialog = new Dialog(this, R.style.Dialog_Fullscreen);
        xxdialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        xxdialog.setCancelable(false);
        iv_quxiao_dismis = (ImageView) headview.findViewById(R.id.iv_quxiao_dismis);
        pricae_tvnum = headview.findViewById(R.id.pricae_tvnum);
        saomiao_surezhifubt = headview.findViewById(R.id.saomiao_surezhifubt);
        Window dialogWindow = xxdialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = DataSingle.getInstance().PhoneW; // 宽度
        // lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);
        iv_quxiao_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                xxdialog.dismiss();
            }
        });
        saomiao_surezhifubt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                xxdialog.dismiss();
                try {
                    if (mima!=null)
                    {
                        mima.setText("");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                xxdialog2.show();
            }
        });
    }

    private void setDialog2() {//支付
        TextView wangjimima;
        LayoutInflater inflater = LayoutInflater.from(this);
        final View headview = inflater.inflate(R.layout.newwalletzhifu_show_dialog2, zhifufubujuly, false);
        xxdialog2 = new Dialog(this, R.style.Dialog_Fullscreen);
        xxdialog2.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        xxdialog2.setCancelable(false);
        mima = headview.findViewById(R.id.zhifu2_pwd);
        wangjimima = headview.findViewById(R.id.wangjimima);
        wangjimima.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                xxdialog2.dismiss();
                startActivity(new Intent(SaomiaoSuccessfukuanActivity.this,ChongzhimimaActivity1.class));
//                finish();
            }
        });
        zhifu2_iv_quxiao_dismis = headview.findViewById(R.id.zhifu2_iv_quxiao_dismis);
        Window dialogWindow = xxdialog2.getWindow();
        //  dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        InputMethodManager imm = (InputMethodManager)
                getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(mima, 0); //显示软键盘
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); //显示软键盘
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = DataSingle.getInstance().PhoneW; // 宽度
        // lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);
        zhifu2_iv_quxiao_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                xxdialog2.dismiss();
            }
        });
        mima.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (mima.length() == 6) {
//                    toastShow(mima.getText().toString());
//                    SaomiaoSuccessfukuanActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                    shoukuanyiquanshu = zhifu_inputnum.getText().toString();
                    tixianyanzheng(mima.getText().toString());
                }
            }
        });
    }

    /**
     * 获取公钥
     */
    private void getgongyaoMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.QRCodeForPayment(params),
                new ApiCallback<QRCodeForPaymentResult>() {

                    @Override
                    public void onSuccess(QRCodeForPaymentResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            String str = model.getData().getPublic_key();
                            String str1 = TextUtils.MD52("DTPOMGHHKJKJA&*((()&").toUpperCase();
                            gongyao = str.replace(str1, "").replace(preferences.getString("token", ""), "");
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                        gongyao = "";
                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }

    //验证付款密码
    private void tixianyanzheng(final String pwd) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("pwd", pwd);
//        showProgressDialog();
        addSubscription(apiStores.CheckPwd(params),
                new ApiCallback<CheckPwdResult>() {

                    @Override
                    public void onSuccess(CheckPwdResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
//                            yzmdialog.dismiss();
//                            tixian();
                            xxdialog2.dismiss();
                            getfukuanMsg(pwd);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }

                    @Override
                    public void onFinish() {
//                        dismissProgressDialog();
                    }
                });
    }

    //付钱
    private void getfukuanMsg(String pwd) {
        showProgressDialog();
        String pinjie = shoukuanname + "@@@" + shoukuanphone + "@@@" + shoukuanyiquanshu;
        String afterencrypt = "";
        PublicKey publicKey = null;
        try {
            publicKey = RSAUtils.loadPublicKey(gongyao);
            byte[] encryptByte = RSAUtils.encryptByPublicKey(pinjie.getBytes(), publicKey);
            afterencrypt = Base64Utils.encode(encryptByte);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Map<String, String> params = new HashMap<>();
            params.put("token", preferences.getString("token", ""));
            params.put("userInfo", afterencrypt);
            params.put("pass", pwd);
            addSubscription(apiStores.YiQuanForScanning(params),
                    new ApiCallback<DatanullResult>() {

                        @Override
                        public void onSuccess(DatanullResult model) {
                            zhifujieguonum = model.getStatus();
                            if (model.getStatus() == Config.SUCCESSCODE) {
                                EventBus.getDefault().post("yiquan3buyok");
                            } else {
                                toastShow(model.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            toastShow(msg);
                        }

                        @Override
                        public void onFinish() {
                            handler.sendEmptyMessageDelayed(0, 0);
                        }
                    });
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            progressDialog.dismiss();
            if (zhifujieguonum == Config.SUCCESSCODE) {
                try {
                    Intent intent = new Intent(SaomiaoSuccessfukuanActivity.this, FukuanSuccessActivity.class);
                    DecimalFormat df = new DecimalFormat("######0");
                    intent.putExtra("txmoney",df.format(Double.parseDouble(shoukuanyiquanshu))+"");
                    startActivity(intent);
//                tv_money.setText(getIntent().getStringExtra("txmoney"));
                    finish();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            } else {
//                toastShow("支付失败");
            }
            return false;
        }
    });
}
